import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, Divider, Form, Icon, Input, message, Radio, Row } from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
import { messages, uniqueObjArr } from 'share/common';
import orderService from 'containers/increment-service/order-management/order-management.service'
import ListSelector from 'components/list-selector';
import SelectAddress from 'components/template/select-address-modal/select-address-modal';
import SelectInvoiceTitle
  from 'components/template/select-invoice-title-modal/select-invoice-title-modal';

class ApplyInvoiceTemplate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      invoiceLoading: false,
      addressLoading: false,
      invoiceTitle: {},    //常用发票抬头
      address: {},            //常用地址
      invoiceType: 'plain',
      selectAddressVisible: false,
      selectInvoiceTitleVisible: false,
      info: this.props.info || {},
      selectOrderList: this.props.selectOrderList || []
    };
    this.addUp = 0;   //订单总金额
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.fromApplyInvoice) {
      this.setState({
        info: nextProps.info || {},
        selectOrderList: nextProps.selectOrderList || []
      })
    }
  }

  componentDidMount() {
    this.getDefaultAddress()
  }

  //获取默认地址   和  默认发票抬头
  getDefaultAddress = () => {
    this.setState({ addressLoading: true, invoiceLoading: true });
    orderService.getDefaultAddress().then(res => {
      this.setState({
        addressLoading: false,
        address: res.data
      })
    }).catch(() => {
      this.setState({ addressLoading: false })
    })
    orderService.getInvoiceTile({page: 0, size: 1}).then(res => {
      if(res.data && res.data.length === 1) {
        if(res.data[0].default) {
          this.setState({
            invoiceTitle: res.data && res.data[0]
          })
        }
      }
      this.setState({
        invoiceLoading: false,
      })
    }).catch(() => {
      this.setState({ invoiceLoading: false })
    })

  };

  checkAmount = () => {
    const { invoiceType, invoiceTitle } = this.state;
    if (invoiceType === 'plain') {
      return (this.addUp >= 100)
    } else if (invoiceType === 'special') {
      return (this.addUp >= 5000)
    }
  };

  //申请发票
  handleApplyInvoice = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.checkAmount()) {
          const { address, invoiceTitle, selectOrderList } = this.state;
          if (!address.billingContactOID) {
            message.error(messages('basic-16.key157')/*请选择收货地址*/)
          } else {
            values.titleType = 'enterprise';
            values.orderIds = selectOrderList.map(item=>item.id);
            values.receiver = address.fullName;
            values.mobile = address.phone;
            values.address = address.fullReceiverAddress;
            values.bankBranchName = invoiceTitle.bankBranchName;
            values.bankId = invoiceTitle.bankId;
            values.title = invoiceTitle.invoiceTitle;
            values.taxNumber = invoiceTitle.taxNumber;
            values.bankAccount = invoiceTitle.bankAccount;
            values.enterpriseMobile = invoiceTitle.enterpriseMobile;
            values.enterpriseAddress = invoiceTitle.enterpriseAddress;
            if(values.invoiceType === 'special') {
              if(!values.bankAccount) {
                message.error(messages('basic-16.key158')/*请完善银行账号信息*/);
                return
              } else if (!values.bankBranchName) {
                message.error(messages('basic-16.key159')/*请完善开户行信息*/);
                return
              } else if (!values.enterpriseMobile) {
                message.error(messages('basic-16.key160')/*请完善电话信息*/);
                return
              } else if (!values.enterpriseAddress) {
                message.error(messages('basic-16.key161')/*请完善地址信息*/);
                return
              }
            }
            this.setState({
              btnLoading: true,
              submitLoading: true,
            });
            orderService.newInvoice(values).then(res => {
              this.setState({
                btnLoading: false,
                submitLoading: false
              }, () => {
                message.success(messages('basic-16.key162')/*申请成功*/);
                this.props.onFinish && this.props.onFinish(res.data);
              })
            }).catch(err => {
              this.setState({
                btnLoading: false,
                submitLoading: false
              });
            })
          }
        } else {
          message.warn(messages('basic-16.key163')/*当前订单实付金额小于开票最小金额，请添加开票订单*/)
        }
      }
    })
  };

  addOrder = () => {
    const { selectOrderList } = this.state;
    ListSelector.open({
      extraParams: {
        orderCodes: selectOrderList.map((item)=>{return item.orderCode}).join(',')
      },
      type: 'increment-order-list',
      labelKey: 'orderCode',
      valueKey: 'id'
    }, this).then(data => {
      const { selectOrderList } = this.state;
      let isHaveOtherOrder = false;
      data && data.forEach((item, index, array)=>{
        if (item.orderType !== 'NEW_BUY' && item.orderType !== 'VALET_ORDER') {
          isHaveOtherOrder = true
        }
        if (index === array.length - 1) {
          if(!isHaveOtherOrder) {
            let result = selectOrderList.concat(data);
            result = uniqueObjArr(result, 'id');
            this.setState({
              selectOrderList: result
            }, ()=>{
              this.props.onChangeOrderList && this.props.onChangeOrderList(result);
            });
          } else {
            message.error(messages('basic-16.key164')/*只允许线上订单开票，请重新选择*/)
          }
        }
      });
    })
  };

  renderTotalAmount = () => {
    const { selectOrderList, info } = this.state;
    const onlyOneOrder = selectOrderList.length === 1;
    let addUp = 0;
    if(onlyOneOrder)
      this.addUp = info.actualAmount;
    return (
      <span>
        {onlyOneOrder ? <div>{this.filterMoney(info.actualAmount  || 0)}{messages('basic-16.key27')/*元*/}</div> :
          <span>
          {selectOrderList.map((item, index, array) => {
            addUp += item.actualAmount;
            this.addUp = addUp;
            return (
              <span>
                <span>
                  {this.filterMoney(item.actualAmount  || 0)}{messages('basic-16.key27')/*元*/}
                </span>&nbsp;{
                (index === array.length - 1) ? '=' : '+'
              }&nbsp;
              </span>
            )
          })}
            <span className="add-up">{this.filterMoney(addUp)}{messages('basic-16.key27')/*元*/}</span>
        </span>}
      </span>
    )
  };

  renderSelectedOrderCode = () => {
    const { selectOrderList } = this.state;
    return (
      <span className="selected-order-list">
        {selectOrderList.map((item, index) => {
          return (
            <div className="single-order">
              <span>{item.orderCode}</span>
              {!!index && <Icon onClick={()=>{this.deleteOrder(index)}} className="icon" type="close-circle" />}
            </div>
          )
        })}
      </span>
    )
  };

  deleteOrder = (index) => {
    const { selectOrderList } = this.state;
    selectOrderList.splice(index, 1);
    this.setState({selectOrderList});
  };

  //选择发票抬头
  handleSelectInvoiceTitle = (value) => {
    this.setState({
      selectInvoiceTitleVisible: false,
      invoiceTitle: value
    })
  };

  //选择收件地址
  handleSelectAddress = (value) => {
    this.setState({
      selectAddressVisible: false,
      address: value
    })
  };

  handleCancel = () => {
    this.props.onCancel && this.props.onCancel();
  }

  render() {
    const { invoiceLoading, invoiceTitle, invoiceType, addressLoading, submitLoading,
      selectAddressVisible, selectInvoiceTitleVisible, address  } = this.state;
    const { fromApplyInvoice } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1}
    };
    const formItemLayout1 = {
      labelCol: {span: 6},
      wrapperCol: {span: 17, offset: 1}
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <div>
        <Form className="invoice-form" onSubmit={this.handleApplyInvoice}>
          <FormItem {...formItemLayout} label={messages('basic-16.key24')/*订单编号*/} colon={false}>
            <div className="order-list">
              <div className="render-com">{this.renderSelectedOrderCode()}</div>
              <Button className="add-order-btn" onClick={this.addOrder} type="primary">{messages('basic-16.key165')/*添加订单*/}</Button>
            </div>
          </FormItem>
          <FormItem {...formItemLayout} wrapperCol={{span: 16, offset: 1}} label={messages('basic-16.key166')/*实付金额*/} colon={false}>
            <div className="total-pay">
              {this.renderTotalAmount()}
            </div>
          </FormItem>
          <Divider/>
          <FormItem {...formItemLayout} label={messages('basic-16.key167')/*抬头类型*/} colon={false}>
            <div>{messages('basic-16.key168')/*企业*/}</div>
          </FormItem>
          <FormItem {...formItemLayout} wrapperCol={{span: 16, offset: 1}} colon={false} label={messages('common.invoice.type')/*发票类型*/}>
            {getFieldDecorator('invoiceType', {
              initialValue: 'plain'
            })(
              <RadioGroup onChange={e => this.setState({ invoiceType: e.target.value })}>
                <Radio value="plain">{messages('basic-16.key52')/*增值税普通发票*/}</Radio>
                <span className="tips">{messages('basic-16.key169',{arg1: 100})/*最小开票金额：{arg1}元*/}</span>
                <Radio value="special">{messages('basic-16.key53')/*增值税专用发票*/}</Radio>
                <span className="tips">{messages('basic-16.key169',{arg1: 5000})/*最小开票金额：{arg1}元*/}</span>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-16.key49')/*开票信息*/} colon={false} >
            {invoiceLoading ? (<Icon type="loading" />)
              : (
                <div>
                  {(invoiceTitle && invoiceTitle.id) ? (
                    <div>
                      <div><a onClick={() => this.setState({selectInvoiceTitleVisible: true})}>{messages('basic-16.key170')/*更改开票信息*/}</a></div>
                      <div className="invoice-title-card">
                        <FormItem {...formItemLayout1} required label={messages('basic-16.key50')/*发票抬头*/} colon={false}>
                          {invoiceTitle.invoiceTitle}
                        </FormItem>
                        <FormItem {...formItemLayout1} required label={messages('basic-16.key171')/*企业税号*/} colon={false}>
                          {invoiceTitle.taxNumber}
                        </FormItem>
                        {invoiceType === 'special' && (
                          <div>
                            <FormItem {...formItemLayout1} required label={messages('basic-16.key172')/*银行账号*/} colon={false}>
                              {invoiceTitle.bankAccount}
                            </FormItem>
                            <FormItem {...formItemLayout1} required label={messages('basic-16.key55')/*开户行*/} colon={false}>
                              {invoiceTitle.bankBranchName}
                            </FormItem>
                            <FormItem {...formItemLayout1} required label={messages('basic-16.key56')/*电话*/} colon={false}>
                              {invoiceTitle.enterpriseMobile}
                            </FormItem>
                            <FormItem {...formItemLayout1} required label={messages('basic-16.key57')/*地址*/} colon={false}>
                              {invoiceTitle.enterpriseAddress}
                            </FormItem>
                          </div>
                        )}
                      </div>
                    </div>
                  ) : (<a onClick={() => this.setState({selectInvoiceTitleVisible: true})}><Icon type="plus" />{messages('basic-16.key173')/*添加开票信息*/}</a>)}
                </div>
              )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={<span className="ant-form-item-required">{messages('basic-16.key174')/*收件信息*/}</span>}
                    colon={false}>
            {getFieldDecorator('receiver')(
              addressLoading ? (
                <Icon type="loading" />
              ) : (
                <div>
                  {address.billingContactOID ? (
                    <div>
                      <div><a onClick={() => this.setState({selectAddressVisible: true})}>{messages('basic-16.key175')/*更改收件地址*/}</a></div>
                      <div>{address.fullName} {address.phone}</div>
                      <div>{address.fullReceiverAddress}</div>
                    </div>
                  ) : (
                    <a onClick={() => this.setState({selectAddressVisible: true})}><Icon type="plus" />{messages('basic-16.key176')/*添加收件地址*/}</a>
                  )}
                </div>
              )
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('basic-16.key61')/*备注temp*/} colon={false}>
            {getFieldDecorator('remark', {
              rules: [{
                required: true,
                message: messages('basic-16.key177')/*请输入temp2*/
              }, {
                max: 100,
                message: messages('basic-16.key178')/*最多输入100个字符*/
              }],
            })(
              <TextArea placeholder={messages('basic-16.key177')/*请输入temp2*/} style={{resize: 'none'}}/>
            )}
          </FormItem>
          <Row>
            <Col span={15} className="buttons">
              <Button className="next" onClick={this.handleCancel}>
                {fromApplyInvoice ? messages('basic-16.key111')/*上一步*/ : messages('common.cancel')/*取消*/}
              </Button>
              <Button type="primary" htmlType="submit" loading={submitLoading}>{messages('basic-16.key179')/*提交申请*/}</Button>
            </Col>
          </Row>
        </Form>
        <SelectAddress visible={selectAddressVisible}
                       selectedOID={address.billingContactOID}
                       onCancel={() => this.setState({selectAddressVisible: false})}
                       onOk={this.handleSelectAddress}
        />
        <SelectInvoiceTitle visible={selectInvoiceTitleVisible}
                            selectedInvoiceOID={invoiceTitle && invoiceTitle.id}
                            onCancel={() => this.setState({selectInvoiceTitleVisible: false})}
                            onOk={this.handleSelectInvoiceTitle}
        />
      </div>
    );
  }
}

ApplyInvoiceTemplate.propTypes = {};

const wrappedApplyInvoiceTemplate = Form.create()(ApplyInvoiceTemplate);

export default wrappedApplyInvoiceTemplate;
